<?php

namespace App\Common\Exception;

use App\Common\Util\Response;
use Psr\Http\Message\ResponseInterface;

/**
 * Class ApiMessageException
 */
class ApiMessageException extends \Exception implements ApiResponseExceptionInterface
{
    /**
     * @param string|array    $message
     * @param int             $code
     * @param \Throwable|null $previous
     */
    public function __construct(string|array $message = "", int $code = 202, ?\Throwable $previous = null)
    {
        if (is_array($message)){
            $message = json_encode($message, JSON_UNESCAPED_UNICODE);
        }

        parent::__construct($message, $code, $previous);
    }

    /**
     * 响应
     *
     * @return \think\Response
     */
    public function response(): \think\Response
    {
        return Response::json()->fail($this->getMessage(), $this->getCode());
    }
}
